//
//  StoreSearchViewController.m
//  iFoundIt
//
//  Created by Navid Shariat on 4/05/10.
//  Copyright 2010 QUT. All rights reserved.
//

#import "StoreSearchViewController.h"
#import "StoreListViewController.h"
#import "StoreMapViewController.h"
#import "WishListViewController.h"
#import "CategoriesViewController.h"
#import "Store.h"
#import "StoreManager.h"
#import "SearchProps.h"

@implementation StoreSearchViewController

@synthesize radiusTextField;
@synthesize keywordTextField;
@synthesize resultTypeSegmentedC;
@synthesize pickCategoryButton;
@synthesize searchButton;
@synthesize locationManager;
@synthesize currentLocation;
@synthesize myActivityView;
@synthesize currentLocationCoordinate;
@synthesize modelView;
@synthesize splashImage;

- (void)dealloc {
	[radiusTextField release];
	[ keywordTextField release];
	[ resultTypeSegmentedC release];
	[ pickCategoryButton release];
	[ searchButton release];	
	[ nextViewController release];
	[locationManager release];
	[myActivityView release];
	[modelView release];
	[splashImage release];
    [super dealloc]; 
	
}



- (void)viewDidLoad {
	[self showSplash];
	myActivityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
	CGRect activityFrame = CGRectMake(130,100,50,50);
	[myActivityView setFrame:activityFrame];
	[self.view addSubview:myActivityView];	
	[self setTitle:@"Search"];	
}

-(void)showSplash
{
	
	UIViewController *modalViewController = [[UIViewController alloc] init];
	
	modalViewController.view = modelView;
	[self presentModalViewController:modalViewController animated:NO];
	NSMutableArray* imageArray = [[NSMutableArray alloc] initWithCapacity:3];
	
	// Build array of images, cycling through image names
	for (int i = 1; i <= 3; i++)
		[imageArray addObject:[UIImage imageNamed:
							   [NSString stringWithFormat:@"moving-%d.tiff", i]]];
	
	[[self splashImage] setAnimationImages: [NSArray arrayWithArray:imageArray]];
	[[self splashImage] setAnimationDuration:4.0];
	[[self splashImage] setAnimationImages: imageArray];
	[[self splashImage] setAnimationRepeatCount:0];
	[[self splashImage] startAnimating]; 
	[self performSelector:@selector(hideSplash) withObject:nil afterDelay:4];
	
}

//hide splash screen

- (void)hideSplash{
	[[self splashImage] stopAnimating]; 	
	[[self modalViewController] dismissModalViewControllerAnimated:YES];
	
}
- (void) addSearchToWishlist{
	WishedItem * wishedItem=[[WishedItem alloc] init];
	[wishedItem setFromLocationCoordinate: [[self currentLocation] coordinate]];
	[wishedItem setSearchKeyword:[[self keywordTextField] text]];
	double radius = [[[self radiusTextField] text] doubleValue];	
	[wishedItem setRadius:radius];
	WishlistPersistentManager* wishlistManager=[[WishlistPersistentManager alloc] init];
	[wishlistManager insertItem:wishedItem];	
//	[wishedItem release];
	[wishlistManager release];
}
- (NSString*)fieldsAreValid{
	NSString* temp=[[self keywordTextField] text];
	if (temp==nil || [temp length]==0){
		return @"Search keyword cannot be empty!";
	}
	temp=[[self radiusTextField] text];
	if (temp==nil || [temp length]==0){
		return @"Radius cannot be empty!";
	}
	return nil;
}

- (void)setKeywordText: (NSString *) text{
	[ keywordTextField setText:text];
	}

-  (void) navigateToMapView: (NSMutableArray *)  stores{
		StoreMapViewController * storeMapViewController= [[StoreMapViewController alloc] initWithNibName:@"StoreMapViewController" bundle:nil];
		[storeMapViewController setFoundPlaces:stores];
	//test
/*	CLLocationCoordinate2D coordinate;
	coordinate.latitude=-27.47328;
	coordinate.longitude=153.02838;
	[storeMapViewController setAlternativeLocationCoordinate:coordinate]; */
	//test end
		[storeMapViewController setAlternativeLocationCoordinate:[self currentLocationCoordinate]]; 	
		[[self navigationController] pushViewController:storeMapViewController animated:YES];
		[storeMapViewController release];			
	}

-  (void) navigateToListView: (NSMutableArray *)  stores{
		StoreListViewController *storeListViewController= [[StoreListViewController alloc] initWithNibName:@"StoreListViewController" bundle:nil];
		
		stores=[self sortFoundStores:stores];
		[storeListViewController setFoundPlaces:stores];
		[storeListViewController setCurrentLocationCoordinate:[self currentLocationCoordinate]];
		[[self navigationController]pushViewController:storeListViewController animated:YES];
		[storeListViewController release];				
	}			

-(NSMutableArray*) sortFoundStores:(NSMutableArray*)stores{
	NSSortDescriptor *sortDescriptor;
	sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"distance" ascending:YES] autorelease];
	NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
	stores = [stores sortedArrayUsingDescriptors:sortDescriptors];
//	[sortDescriptor release];	
//	[sortDescriptors release];	
	return stores;
}
#pragma mark Actions
-(IBAction)textFieldDoneEditing:(id)sender{
	[sender resignFirstResponder];
}

- (IBAction) backgroundPressed{
	//hides both keyboards
	[[self radiusTextField] resignFirstResponder];
	[[self keywordTextField] resignFirstResponder];
	
}


#pragma mark Buttons	
	- (IBAction) searchButtonPressed:(id) sender{
/*		UIActionSheet * actionSheet = [[UIActionSheet alloc]initWithTitle: @"11111"
												 delegate:self
										cancelButtonTitle:@"CANCEL111"	
								   destructiveButtonTitle:@"blue" 
										otherButtonTitles:@"Other", nil];
		
		[actionSheet showInView:[self view]];
		[actionSheet release];	*/	
		NSString*msg= [self fieldsAreValid];
		if (!msg)
		{
			[[self searchButton] setEnabled:NO];
			[myActivityView startAnimating];
			[self initLocationManager];
		}
		else
		{
			UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"Empty required filed"
															message: msg
														   delegate: nil
												  cancelButtonTitle: @"OK"
												  otherButtonTitles: nil];
			
			[alert show];
			[alert release];
		}
	}
	

- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex {
	if (buttonIndex != [actionSheet cancelButtonIndex]){
		[self addSearchToWishlist];
		UIAlertView * alert=[[UIAlertView alloc] initWithTitle:@"Done" message:@"Item added to your wishlist!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alert show];
		[alert release];
	}
	
}

- (IBAction) pickCategoryButtonPressed:(id) sender {
	[self backgroundPressed];
	CategoriesViewController *categoriesViewController= [[CategoriesViewController alloc] initWithNibName:@"CategoriesViewController" bundle:nil];
	[categoriesViewController setSearchView:self];
	[[self navigationController]pushViewController:categoriesViewController animated:YES];
	[categoriesViewController release];		
	
	/*
	[UIView beginAnimations:@"flipping view" context:nil];
    [UIView setAnimationDuration:1];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
	[UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:self.view cache:YES];
    
	[self backgroundPressed];
    [[self view] addSubview:[nextViewController view]];
    [UIView commitAnimations];
	 */
}

	

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (CLLocationManager *)locationManager {
    if (locationManager != nil) {
        return locationManager;
    }
    locationManager = [[CLLocationManager alloc] init];
    locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
    locationManager.delegate = self;	
    return locationManager;
}

- (void) findStores{
	double radius = [[[self radiusTextField] text] doubleValue]*1000;	
	StorePersistentManager* stPManager=[[StorePersistentManager alloc] init];
//	NSMutableArray* foundStores= [stPManager findStores:[searchProps searchKeyword]];
	NSMutableArray* foundStores= [stPManager findStores:[[self keywordTextField] text]: [self currentLocation]: radius];	
	if ([foundStores count]!=0)
	{
		[self navigateTo:foundStores];
//		[foundStores release];
	}
	else{
		UIActionSheet * actionSheet = [[UIActionSheet alloc]initWithTitle: @"No store found! Do you want to add this search to your Wish List? "
		delegate:self
		cancelButtonTitle:@"No"	
		destructiveButtonTitle:@"Yes"
														otherButtonTitles:nil,
		nil];		 
		[actionSheet showInView:[self view]];
		[actionSheet release];
		
	}		
	[stPManager release];
}

-  (void) navigateTo: (NSMutableArray *) stores{
	NSUInteger index= [[self resultTypeSegmentedC] selectedSegmentIndex ] ;
	if (index==0){
		[self navigateToListView: stores];
	}
	else{
		[self navigateToMapView:stores];			
	}
}

#pragma mark CLLocationDelegates
-(void)initLocationManager{
	CLLocationManager *locMan = [[CLLocationManager alloc] init];
	[locMan setDelegate:self];
	[locMan setDistanceFilter:10.0f];
	[locMan setDesiredAccuracy:kCLLocationAccuracyBest];
	[self setLocationManager:locMan];
	[locMan release];
	// Once configured, the location manager must be "started".
	[[self locationManager] startUpdatingLocation];	
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
	[manager stopUpdatingLocation];	
	[self setCurrentLocation:newLocation];
	[self setCurrentLocationCoordinate:[newLocation coordinate]];
	[self findStores];
	[[self searchButton] setEnabled:YES];	
	[myActivityView stopAnimating];
}

@end
